class ApplicationController < ActionController::Base
	# Prevent CSRF attacks by raising an exception.
	# For APIs, you may want to use :null_session instead.
	protect_from_forgery with: :exception


	def list_filter_scope
		@titles = []
		#先找到认证的资源
		@movies = Movie.verified

		unless params[:country].blank?
			@movies = @movies.tagged_with_on(:countries, params[:country])
			@titles << params[:country]
		end

		unless params[:category].blank?
			@movies = @movies.tagged_with_on(:categories, params[:category])
			@titles << params[:category]
		end

		unless params[:year].blank?
			@filter_year = params[:year].to_i
			@movies = @movies.where(:year => @filter_year)
			@titles << params[:year]
		end

		unless params[:language].blank?
			@movies = @movies.tagged_with_on(:languages, params[:language])
			@titles << params[:language]
		end

		unless params[:actor].blank?
			@movies = @movies.tagged_with_on(:actors, params[:actor])
			@titles << params[:actor]
		end

		unless params[:director].blank?
			@movies = @movies.tagged_with_on(:directors, params[:director])
			@titles << params[:director]
		end

		case params[:sort]
		when "recent"
			@movies = @movies.newest
		when "rank"
			@movies = @movies.high_rank
		else
			@movies = @movies.recent_upload
		end
		@movies
	end

	def current_user
		if session[:user_id]
			@current_user ||= User.find(session[:user_id])
		else
			nil
		end
	end

	def admin?
		@user = current_user
		return @user.admin
	end

	def authericate_user
		if current_user.blank? || current_user.nil?
			redirect_to login_users_path
		elsif current_user.admin?
      redirect_to login_users_path
		end
	end

	def render_page_title
		site_name = Setting.app_name
		title = @page_title ? "#{site_name} | #{@page_title}" : site_name rescue "SITE_NAME"
		content_tag("title", title, nil, false)
	end

	def set_seo_meta(title = '',meta_keywords = '', meta_description = '')
		if !title.blank?
			@page_title = "#{title}"
			if !params[:page].blank?
				@page_title += " [第#{params[:page]}页]"
				drop_breadcrumb("第#{params[:page]}页")
			end
		end
		@meta_keywords = meta_keywords
		@meta_description = meta_description
	end

	def fresh_when(opts = {})
		opts[:etag] ||= []
		# 保证 etag 参数是 Array 类型
		opts[:etag] = [opts[:etag]] if !opts[:etag].is_a?(Array)
		# 加入页面上直接调用的信息用于组合 etag
		opts[:etag] << current_user
		opts[:etag] << @page_title
		opts[:etag] << @meta_keywords
		opts[:etag] << @meta_description
		# etag 最长时效为一个星期
		opts[:etag] << Time.now.strftime("%Y%m%d")
		opts[:etag] << flash
		opts[:etag] << "v222"
		super(opts)
	end



end
